package com.tiancheng.trade.payment.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.Optional;

/**
 * 对象转换工具类
 *
 * @author kellen
 * @date 2024/1/2
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ObjectConvertUtil {

    /**
     * 转换对象
     *
     * @param resource {@link Object}
     * @param target   {@link Class}
     * @param ignores  String...
     * @return T
     */
    public static <T> Optional<T> convert(Object resource, Class<T> target, String... ignores) {
        try {
            T t = target.newInstance();
            if (resource != null) {
                BeanUtils.copyProperties(resource, t, ignores);
            }
            return Optional.of(t);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Optional.empty();
        }
    }

    /**
     * 转换对象
     *
     * @param resource {@link Object}
     * @param target   {@link Object}
     * @param clazz    {@link Class}
     * @param ignores  String...
     * @return T
     */
    public static <T> Optional<T> convert(Object resource, Object target, Class<T> clazz, String... ignores) {

        try {
            if (resource != null) {
                BeanUtils.copyProperties(resource, target, ignores);
            }
            return Optional.of((T) target);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Optional.empty();
        }
    }
}
